<?php
class ControllerSmsTianyi extends Controller {
  public function getrandchar($len) {
    $chars = array (
        "0",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9" 
    );
    $charslen = count ( $chars ) - 1;
    shuffle ( $chars );
    $output = "";
    for($i = 0; $i < $len; $i ++) {
      $output .= $chars [mt_rand ( 0, $charslen )];
    }
    return $output;
  }
  public function create_mobile_code() {
    $this->load->language ( 'sms/chengyu' );
    
    $this->load->model ( 'account/smsmobile' );
    
    $this->load->model ( 'account/customer' );
    
    $json = array ();
    
    if ($this->request->server ['REQUEST_METHOD'] == 'POST') {
      if ((utf8_strlen ( trim ( $this->request->post ['telephone'] ) ) != 11) || (! is_numeric ( $this->request->post ['telephone'] ))) {
        $json ['error'] = $this->language->get ( 'error_telephone' );
      }
      
      // if telephone already registered:
      if ($this->model_account_customer->getTotalCustomersByTelephone ( $this->request->post ['telephone'] )) {
        $json ['error'] = $this->language->get ( 'error_telephone_registered' );
      }
      $data = $this->model_account_smsmobile->getIdBySmsMobile ( trim ( $this->request->post ['telephone'] ) );
      if ($data && $data ['create_time']) {
        $create_time = strtotime ( $data ['create_time'] );
        if (time () - $create_time < 60) {
          $json ['error'] = $this->language->get ( 'error_time' );
        }
      }
      if (! isset ( $json ['error'] )) {
        $verify_code = $this->getrandchar ( 6 );
        
        $this->model_account_smsmobile->deleteSmsMobile ( trim ( $this->request->post ['telephone'] ) );
        
        $this->model_account_smsmobile->addSmsMobile ( trim ( $this->request->post ['telephone'] ), $verify_code );
        
        $post_data = array ();
        $appId = $this->config->get ( 'tianyi_appid' );
        $appSecret = $this->config->get ( 'tianyi_appsecret' );
        $templateId = $this->config->get ( 'tianyi_templateid' );
        // $post_data['content'] = urlencode(sprintf($this->language->get('text_content'), $verify_code));

        $template_param = json_encode ( array (
            "code" => $verify_code,
            "time" => 60
        ) );
        $res = self::sendSms($appId, $appSecret, $templateId, trim ( $this->request->post ['telephone'] ), $template_param);
        if($res == 'successful'){
          $json ['success'] = $this->language->get ( 'text_success' );
        }
        else{
          $json ['error'] = $res;
        }
      }
    }
    $this->response->setOutput ( json_encode ( $json ) );
  }

  private static function sendSms($appId, $appSecret, $templateId, $phone, $tempParam){
    date_default_timezone_set ( 'Asia/Shanghai' );
    if(is_array($tempParam)){
      $tempParam = json_encode($tempParam);
    }
    $timestamp = date ( 'Y-m-d H:i:s' );
    $grant_type = "client_credentials";
    // 获取Accesss Token
    $url = "https://oauth.api.189.cn/emp/oauth2/v3/access_token";
    $postdata = 'app_id=' . $appId . '&app_secret=' . $appSecret . '&grant_type=' . $grant_type;
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postdata );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
    $data = curl_exec ( $ch );
    curl_close ( $ch );
    $data = json_decode ( $data, true );
    $access_token = $data ['access_token'];
    if(!$access_token){
      return "获取access_token失败: ".$data['res_message'];
    }
    // 发送模板短信
    $url = "http://api.189.cn/v2/emp/templateSms/sendSms";
    $postdata = 'timestamp=' . $timestamp . '&acceptor_tel=' . $phone . '&template_id=' . $templateId . '&template_param=' . $tempParam . '&app_id=' . $appId . '&access_token=' . $access_token;
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postdata );
    $data = curl_exec ( $ch );
    curl_close ( $ch );
    $data = json_decode ( $data, true );
    if ($data ['res_code'] === 0) {
      return "successful";
    } else {
      return $data ['res_message'];
    }
  }
}